import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { DatePicker, Icon, Button, Select, notification, Input } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import { fileDownload } from '@/utils/downExcel';
import { useBoolean, useRequest } from '@umijs/hooks';
import AuthComponent from '@/components/Authorized/AuthComponent';
import { queryStatement, queryCityInfo, markItem, exportChart } from './service';
import moment from 'moment';
import './index.less';
const { Option } = Select;

let hiddenData = null;
const TableList = () => {

  const [height, controlH] = useState(300);
  const [isCollapse, controlC] = useState(true);
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 364.5);
    } else {
      controlH(document.body.clientHeight - 588.5);
    }
  }, [isCollapse])
  // 到达航站，出发航站搜索数据
  const { data: selectData } = useRequest(queryCityInfo);

  // 储存搜索条件
  const [saveSearchData, handleSearchData] = useState({});

  // 标记按钮状态
  const {
    state: markState,
    setTrue: setMarkTrue,
    setFalse: setMarkFalse,
  } = useBoolean(true);

  const {
    state: exportState,
    setTrue: setExportTrue,
    setFalse: setExportFalse,
  } = useBoolean(false);

  // 标记和取消标记
  const { loading: markLoading, run } = useRequest(params => markItem(params), {
    manual: true,
    onSuccess: () => {
      notification.success({
        message: '成功',
        duration: 3,
        description: '操作完成',
      });
      setMarkTrue();
      actionRef.current.reload();
    },
  });

  // 第一次加载
  const [firstLoadDate, setFirstLoadDate] = useState(true)
  const [firstLoadPayDate, setFirstLoadPayDate] = useState(true)
  // 记录表格选中的Ids
  const [ids, handleIds] = useState([]);

  // 标记 或 取消标记方法
  const markOr = status => {
    run({
      ids: ids.join(','),
      status,
    });
  };

  // 导出报表
  const { run: runExport } = useRequest(params => exportChart(params), {
    manual: true,
    onSuccess: data => {
      fileDownload(
        data,
        `航延报表${moment().year()}${moment().month() +
          1}${moment().date()}${moment().hour()}${moment().minute()}${moment().second()}`,
      );
    },
  });
  const exportCharts = () => {
    runExport(saveSearchData);
  };

  const actionRef = useRef();
  const ref = useRef();
  const rowSelection = {
    onChange: selectedRowKeys => {
      selectedRowKeys.length ? setMarkFalse() : setMarkTrue();
      handleIds(selectedRowKeys);
    },
  };
  const formatFlightNo = (val) => {
    if (!val) {
      return '';
    } else if (val.length < 3 || /^\D/.test(val)) {
      return ''.toUpperCase.call(val);
    } else if (/^\d{2}/.test(val)) {
      return `3U${val}`;
    } else {
      return val;
    }
  }
  const columns = [
    {
      title: '标记',
      hideInSearch: true,
      dataIndex: 'isFlag',
      render: text => {
        if (Number(text)) {
          return <Icon type="check-circle" />;
        } else {
          return <></>;
        }
      },
      width: 80
    },
    {
      title: '航班号',
      dataIndex: 'flightNo',
      order: 16,
      width: 100,
      renderFormItem: (_, { type, defaultRender, ...rest }) => {
        return <Input 
          {...rest}
          onChange= {e => {
            e.target.value = formatFlightNo(e.target.value);
            rest.onChange(e.target.value)
          }}
          allowClear maxLength={6} placeholder="3U" />;
      },
    },
    {
      title: '航班日期',
      dataIndex: 'flightDate',
      hideInSearch: true,
      width: 120
    },
    {
      title: '航班开始日期',
      hideInTable: true,
      dataIndex: 'flightStartDate',
      order: 18,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航班结束日期',
      hideInTable: true,
      dataIndex: 'flightEndDate',
      order: 17,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航段',
      dataIndex: 'segment',
      hideInSearch: true,
      width: 150
    },
    {
      title: '补偿类型',
      dataIndex: 'payType',
      filters: [
        {text: '不正常航班',value: '不正常航班'},
        {text: '异常行李', value: '异常行李'},
        {text: '旅客超售', value: '旅客超售'},
      ],
      valueEnum: {
        '': {
          text: '全部',
        },
        '0': {
          text: '不正常航班',
        },
        '1': {
          text: '异常行李',
        },
        '2': {
          text: '旅客超售',
        },
      },
      width: 120
    },
    {
      title: '延误原因',
      dataIndex: 'lateReason',
      hideInSearch: true,
      width: 180
    },
    // 延误时长
    {
      title: '延误时长',
      dataIndex: 'delayTime',
      hideInSearch: true,
      width: 120
    },
    {
      title: '补偿单编号',
      dataIndex: 'orderId',
      hideInSearch: true,
      width: 180
    },
    {
      title: '支付状态',
      hideInTable: true,
      dataIndex: 'payStatus',
      filters: [
        {text: '未支付',value: '未支付'},
        {text: '支付成功', value: '支付成功'},
        {text: '支付失败', value: '支付失败'},
      ],
      valueEnum: {
        '': {
          text: '全部',
        },
        '0': {
          text: '未支付',
        },
        '1': {
          text: '支付成功',
        },
        '2': {
          text: '支付失败',
        },
      },
    },
    {
      title: '支付失败原因',
      dataIndex: 'payFailRemark',
      hideInSearch: true,
      width: 200
    },
    {
      title: '旅客搜索',
      dataIndex: 'keySearch',
      hideInTable: true,
    },
    {
      title: '领取状态',
      dataIndex: 'receiveStatus',
      filters: [
        {text: '已领取', value: '已领取'},
        {text: '未领取',value: '未领取'},
        {text: '已逾期', value: '已逾期'},
      ],
      valueEnum: {
        '': {
          text: '全部',
        },
        '1': {
          text: '已领取',
        },
        '0': {
          text: '未领取',
        },
        '3': {
          text: '已逾期',
        },
      },
      width: 100
    },
    {
      title: '领取渠道',
      dataIndex: 'receiveChannel',
      filters: [
        {text: '普通',value: '普通'},
        {text: '代领', value: '代领'},
        {text: '现金', value: '现金'},
      ],
      valueEnum: {
        '': {
          text: '全部',
        },
        '2': {
          text: '现金',
        },
        '1': {
          text: '代领',
        },
        '0': {
          text: '普通',
        },
      },
      width: 100
    },
    {
      title: '支付方式',
      dataIndex: 'receiveWay',
      filters: [
        {text: '微信',value: '微信'},
        {text: '银联', value: '银联'},
        {text: '现金', value: '现金'},
      ],
      valueEnum: {
        '': {
          text: '全部',
        },
        '0': {
          text: '微信',
        },
        '1': {
          text: '银联',
        },
        '2': {
          text: '现金',
        },
      },
      width: 120
    },
    {
      title: '服务航站',
      dataIndex: 'serviceCity',
      width: 150,
      renderFormItem: (item, { ...rest }) => {
        return (
          <Select
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>;
              })}
          </Select>
        );
      },
    },
    {
      title: '出发航站',
      dataIndex: 'orgCity',
      renderFormItem: (item, { ...rest }) => {
        return (
          <Select
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>;
              })}
          </Select>
        );
      },
      width: 150
    },
    {
      title: '到达航站',
      dataIndex: 'dstCity',
      renderFormItem: (item, { ...rest }) => {
        return (
          <Select
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>;
              })}
          </Select>
        );
      },
      width: 150
    },
    {
      title: '支付时间',
      dataIndex: 'payDate',
      hideInSearch: true,
      width: 180
    },
    {
      title: '支付开始时间',
      hideInTable: true,
      dataIndex: 'payStartDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '支付结束时间',
      hideInTable: true,
      dataIndex: 'payEndDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '补偿单状态',
      dataIndex: 'orderStatus',
      filters: [
        {text: '通过',value: '通过'},
        {text: '生效', value: '生效'},
        {text: '关闭', value: '关闭'},
      ],
      valueEnum: {
        '': {
          text: '全部',
        },
        '2': {
          text: '通过',
        },
        '3': {
          text: '生效',
        },
        '4': {
          text: '关闭',
        },
      },
      width: 120
    },
    {
      title: '开户名',
      dataIndex: 'accountName',
      hideInSearch: true,
      render: (text, record) => {
        return <span>{record.receiveWay === '银联'?text:''}</span>
      },
      width: 120
    },
    {
      title: '开户行',
      dataIndex: 'openBankName',
      hideInSearch: true,
      width: 120
    },
    {
      title: '账号',
      dataIndex: 'getAccount',
      hideInSearch: true,
      ellipsis:true,
      width: 250
    },
    {
      title: '旅客姓名',
      dataIndex: 'paxName',
      hideInSearch: true,
      width: 120
    },
    {
      title: '票号',
      dataIndex: 'tktNo',
      hideInSearch: true,
      width: 150
    },
    {
      title: '总金额',
      dataIndex: 'totalPay',
      hideInSearch: true,
      width: 120
    },
    {
      title: '补偿金额',
      dataIndex: 'payMoney',
      hideInSearch: true,
      width: 120
    },
    {
      title: '客票差价',
      dataIndex: 'tktPriceDiff',
      hideInSearch: true,
      width: 120
    },
    {
      title: '地区类型',
      dataIndex: 'dori',
      hideInSearch: true,
      filters: [
        {text: '国内',value: 'D'},
        {text: '国际', value: 'I'},
        {text: '地区', value: 'R'},
      ],
      valueEnum: {
        '': {
          text: '全部',
        },
        'D': {
          text: '国内',
        },
        'I': {
          text: '国际',
        },
        'R': {
          text: '地区',
        },
      },
      width: 120
    },
    {
      title: '支付流水号',
      hideInSearch: true,
      dataIndex: 'paySerialNum',
      width: 150
    },
    {
      title: '到期日期',
      dataIndex: 'expireTime',
      hideInSearch: true,
      width: 180
    },
    {
      title: '申请人',
      dataIndex: 'applyUser',
      hideInSearch: true,
      width: 120
    },
    {
      title: '审核人',
      dataIndex: 'lastAuditor',
      hideInSearch: true,
      width: 120
    },
    {
      title: '机型',
      dataIndex: 'acType',
      width: 90
    },
    {
      title: '代领旅客审核状态',
      dataIndex: 'actStatus',
      filters: [
        {text: '待审核',value: '待审核'},
        {text: '通过', value: '通过'},
        {text: '未通过', value: '未通过'},
      ],
      valueEnum: {
        '': {
          text: '全部',
        },
        '0': {
          text: '待审核',
        },
        '1': {
          text: '通过',
        },
        '2': {
          text: '未通过',
        },
      },
      width: 150
    },
    {
      title: '标记',
      dataIndex: 'isFlag',
      hideInTable: 'true',
      filters: [
        {text: '未标记',value: '0'},
        {text: '已标记', value: '1'}
      ],
      valueEnum: {
        '': {
          text: '全部',
        },
        '0': {
          text: '未标记',
        },
        '1': {
          text: '已标记',
        }
      },
    },
  ];
  const beforeSearchSubmit = (params)=> {
    console.log('beofre', params);
    if (!isCollapse) {
      handleSearchData(params);
      return params
    } else {
      if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('flightStartDate') === -1) {
          params.flightStartDate = ''
        }
        if (Object.keys(params).indexOf('flightEndDate') === -1) {
          params.flightEndDate = ''
        }
      } else if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
        hiddenData = {}
      }
      handleSearchData({...hiddenData, ...params});
      return {...hiddenData, ...params}
    }
  }

  return (
    <>
      <ProTable
        formRef={ref}
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        size="small"
        onLoad={data => {
          if (data.length) {
            setExportFalse()
          } else {
            setExportTrue()
          }
        }}
        className={`rest-pro-table-form-compact ${isCollapse?'':'collapse'}`}
        headerTitle={
          <div>
            <span style={{ paddingRight: 10, fontWeight: 'bold', color: '#000' }}>
              补偿申请单列表
            </span>
          </div>
        }
        actionRef={actionRef}
        beforeSearchSubmit={beforeSearchSubmit}
        rowKey="id"
        rowSelection={rowSelection}
        scroll={{ x: 1000, y: height }}
        toolBarRender={(action, { selectedRows }) => [
          <>
            <AuthComponent authCode="report.index.flag">
              <Button
                loading={markLoading}
                onClick={() => markOr(1)}
                disabled={markState}
                style={{ marginRight: '10px' }}
                icon="check-circle"
                type="primary"
              >
                标记
              </Button>
              <Button
                loading={markLoading}
                onClick={() => markOr(0)}
                disabled={markState}
                style={{ marginRight: '10px' }}
                icon="rollback"
                type="primary"
              >
                取消标记
              </Button>
              </AuthComponent>
              <AuthComponent authCode="report.index.export">
              <Button disabled={exportState} onClick={() => exportCharts()} icon="download" type="primary">
                导出
              </Button>
            </AuthComponent>
          </>,
        ]}
        search={{
          onCollapse: val => {
            controlC(val);
            if (!val && hiddenData) {
              ref.current.setFieldsValue({
                flightNo: hiddenData.flightNo,
                payType: hiddenData.payType,
                payStatus: hiddenData.payStatus,
                keySearch: hiddenData.keySearch,
                receiveStatus: hiddenData.receiveStatus,
                receiveChannel: hiddenData.receiveChannel,
                receiveWay: hiddenData.receiveWay,
                serviceCity: hiddenData.serviceCity,
                orgCity: hiddenData.orgCity,
                dstCity: hiddenData.dstCity,
                payStartDate: hiddenData.payStartDate ? moment(hiddenData.payStartDate) : '',
                payEndDate: hiddenData.payEndDate ? moment(hiddenData.payEndDate) : '',
                orderStatus: hiddenData.orderStatus,
                areaType: hiddenData.areaType,
                acType: hiddenData.acType,
                actStatus: hiddenData.actStatus,
                isFlag: hiddenData.isFlag
              })
            } else {
              hiddenData = ref.current.getFieldsValue()
            }
          }
        }}
        request={params => {
          console.log('req', params)
          if (!params['flightStartDate'] && !params['flightEndDate'] && firstLoadDate) {
            console.log(params);
            setFirstLoadDate(false)
            ref.current.setFieldsValue({
              flightStartDate: moment(),
              flightEndDate: moment()
            })
            params['flightStartDate'] = moment().format('YYYY-MM-DD');
            params['flightEndDate'] = moment().format('YYYY-MM-DD');
          } else {
            params['flightStartDate'] = params.flightStartDate ? params.flightStartDate.format('YYYY-MM-DD') : '';
            params['flightEndDate'] = params.flightEndDate ? params.flightEndDate.format('YYYY-MM-DD') : '';
          }
        
          if (!params['payStartDate'] && !params['payEndDate'] && firstLoadPayDate) {
            setFirstLoadPayDate(false)
            ref.current.setFieldsValue({
              payStartDate: moment(),
              payEndDate: moment()
            })
            params['payStartDate'] = moment().format('YYYY-MM-DD');
            params['payEndDate'] = moment().format('YYYY-MM-DD');
          } else {
            params['payStartDate'] = params.payStartDate ? params.payStartDate.format('YYYY-MM-DD') : '';
            params['payEndDate'] = params.payEndDate ? params.payEndDate.format('YYYY-MM-DD') : '';
          }
       
          if (!params['payType']) {
            ref.current.setFieldsValue({
              payType: ''
            })
          }
          if (!params['payStatus']) {
            ref.current.setFieldsValue({
              payStatus: ''
            })
          }
          if (!params['receiveStatus']) {
            ref.current.setFieldsValue({
              receiveStatus: ''
            })
          }
          if (!params['receiveChannel']) {
            ref.current.setFieldsValue({
              receiveChannel: ''
            })
          }
          if (!params['receiveWay']) {
            ref.current.setFieldsValue({
              receiveWay: ''
            })
          }
          if (!params['orderStatus']) {
            ref.current.setFieldsValue({
              orderStatus: ''
            })
          }
          if (!params['areaType']) {
            ref.current.setFieldsValue({
              areaType: ''
            })
          }
          if (!params['actStatus']) {
            ref.current.setFieldsValue({
              actStatus: ''
            })
          }
          if (!params['isFlag']) {
            ref.current.setFieldsValue({
              isFlag: ''
            })
          }
          console.log('request1', params);
          return queryStatement(params)
        }}
        columns={columns}
      />
      
    </>
  );
};
export default Form.create()(TableList);
